<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>{{ $t('report.statistics.title29') }}
        <el-popover trigger="hover">
          <div class="stats-popover-row">
            <div class="stats-popover-label">{{$t('report.taskTeamChart.state1')}}：</div>
            <div class="stats-popover-text">{{ $t('report.stationTable.title1') }}</div>
          </div>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
     
      <biz-team-select class="stats-team-select biz-team-select" is-auto-select-child collapse multiple :value="tag" @input="chooseTeam" :fetch-func="fetchTeam"/>
    </div>
    <div class="stats-panel-body"> 
      <div id="team-chart"></div>
      <stats-chart-empty v-if="empty">{{$t('common.base.tip.noData')}}</stats-chart-empty>
      <div class="stats-task-table-wrap" v-if="showTable">
        <div class="stats-task-table-header">
          <h3>{{ $t('report.stationTable.title2') }}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button> 
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button> 
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div class="stats-task-table">
          <el-table :data="page.list" class="stats-table">

            <el-table-column :label="$t('common.base.serialNumber')" prop="eventNo" width="150px" :show-overflow-tooltip="false">
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.eventNo" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(scope.row)">{{scope.row.eventNo}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="cusName"></el-table-column>
            <el-table-column :label="$t('common.label.eventType')" prop="templateName" width="180px"></el-table-column>

            <el-table-column :label="$t('common.base.status')" width="180px">
              <template slot-scope="scope">
                {{formatState(scope.row.state)}}
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.label.principalName')" width="120px">
              <template slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executorName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.base.createUser')" width="120px">
              <template slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.createUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUserName }}
                </template>
              </template>
            </el-table-column>
 
          </el-table>

          <el-pagination class="stats-pagination"
                         background @current-change="jump"
                         :current-page="page.pageNum"
                         layout="total, prev, pager, next"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
/* global AMap, moment, _init_data*/
import _ from 'lodash';
import qs from 'src/util/querystring';

import http from 'src/util/HttpUtil';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import echarts from 'packages/Echarts';
import SampleTooltip from 'packages/SampleTooltip';
import { checkButtonDisplayed } from '@src/util/dom';
import { fetchNoFinishedEvents, fetchNoFinishedEventsList } from '@src/api/EventApi';
let chart = null;
import { t } from '@src/locales';
export default {
  name: 'station-table',
  props: {
    chartType: {
      type: String,
      default: ''
    },
    exportTrack: {
      type: Function,
      default: (() => {})
    }
  },
  data(){
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      tag: [],
      pieData: {},
      sort: '',
      timeStart: '',
      timeEnd: '',
      empty: false,

      showTable: false,
      model: {
        pageNum: 1,
        selectType: '',
        tagId: ''
      },
      teamId: '',
      page: {}
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
  },
  methods: {
    fetchTeam(params){
      return this.$http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    chooseTeam(value){
      this.$tdOnEvent('pc：事件报表-选择团队事件');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};

      let tag = value
      this.tag = value;
      this.teamId = tag.map(item => {return item.id}).join(',');

      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    exportAllData(){
      let model = {
        // executor: this.model.executor,
        tagId: this.teamId,
        isAll: true,
        pageSize: 0
      };

      window.location.href = `/event/sum/noFinishedEvents/export?${ qs.stringify(model)}`;

      this.exportTrack(true, false)
    },
    exportData(){
      let model = {
        executor: this.model.executor,
        tagId: this.teamId,
        pageSize: 0,
        isAll: true
      };

      window.location.href = `/event/sum/noFinishedEvents/export?${ qs.stringify(model)}`;

      this.exportTrack(false, false)
    },
    exportTrack(isExportAll) {
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType,
      }, '*')
    },
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `eventView_${ row.id}`, 
      //   title: `事件${row.eventNo}`, 
      //   close: true, 
      //   url: `/event/view/${row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: row.id,
        titleKey: row.eventNo,
        fromId
      })
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    chooseDate(start, end){
      this.$emit('trackEvent', 'chooseDate');

      this.timeStart = start.format('YYYY-MM-DD');
      this.timeEnd = end.format('YYYY-MM-DD');
      this.render();
    },
    async render(){
      try {

        let instance = this.$loading.show(this.$el);
        
        let data = await this.fetchData();

        instance.hide();
        // 隐藏表格
        this.showTable = false;
      
        let option = this.getOption(data.data || []);
        if(null == option) {
          this.empty = true;
          return
        }
        chart.setOption(option);
      } catch (error) {
        console.log(error)
      }
    },
    fetchData(){
      let model = {}
      if(this.teamId){
        model.tagId = this.teamId;
      }
      return fetchNoFinishedEvents(model).then(async res=>{
        if (this.isOpenData) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          
          let originItems = (res.data || []).filter(item=>item.executorName)
          let items = originItems.map(item => {
            return {
              type: 'userName',
              id: item.executorStaffId
            }
          })
          const result = await new Promise((resolve, reject) => {
            window.WWOpenData.prefetch({ items }, (err, data) => {
              if (err) {
                return reject(err)
              }
              resolve(data)
            })
          })
          
          try {
            res.data = originItems.map((item, index) => {
              return Object.assign(item, { executorName: result.items[index].data })
            })
          } catch (error) {
            console.warn(error)
          }
        }

        return res
      });
    },
    getOption(data = []){
      let ctx = this;
      if(!data) return null;
      data = data.filter(item => {
        return item.count > 0
      })

      chart.clear();
      if(data.length == 0) return null;

      this.empty = false;

      let legend = [t('report.taskTeamChart.state1')];
      
      let xAxisData = [];
      let unFinishedData = [];

      let series = [];

      data.sort((prev, next) => {
        return next.count - prev.count
      }).forEach(item => {
        xAxisData.push(!item.executorName ? '无' : item.executorName);

        unFinishedData.push({
          name: t('report.taskTeamChart.state1'),
          value: item.count,
          _origin: item
        });
      })

      let dataZoomShow = false;
      let start = 0;
      let end = xAxisData.length - 1;
      if(xAxisData.length > 10){
        end = 9;
        dataZoomShow = true;
      }
      
      series.push({
        name: t('report.taskTeamChart.state1'),
        type: 'bar',
        barMaxWidth: 30,
        data: unFinishedData,
        barCategoryGap: '30px',
        itemStyle: { normal: {label : {show: true}}}
      })

      return {
        color: ['#2ec7c9', '#ffb980'],
        tooltip : {
          trigger: 'axis',
          axisPointer : {           
            type : 'shadow'       
          },
          formatter: data => {
            let html = '';
            if(ctx.isOpenData) {
              let staffId = data[0].data._origin.executorStaffId
              let id = Math.ceil(Math.random() * 1000)
              html = `<ww-open-data type="userName" openid="${staffId}" id="wwOpenData${id}"></ww-open-data>`
              setTimeout(() => {
                window.WWOpenData && window.WWOpenData.bind(document.getElementById(`wwOpenData${id}`))
              }, 500);
            }else {
              let name = data[0].axisValue;
              html += `<div>${name}</div>`;
            }

            data.forEach(item => {
              html += `<div>${item.marker} ${item.seriesName}: ${item.value}</div>`;
            })

            return html;
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: t('report.stationTable.title3'),
            }
          },
          top: 10,
          right: 40
        },
        legend: {
          top: 10,
          left: 50,
          data: legend
        },
        dataZoom: [{
          type: 'slider',
          show: dataZoomShow,
          xAxisIndex: 0,
          startValue: start,
          endValue: end,
          bottom: '10px'
        }],
        grid: {
          top: 60,
          left: '50px',
          right: '40px',
          bottom: '60px',
          containLabel: true
        },
        xAxis : [
          {
            type: 'category',
            data: xAxisData
          }
        ],
        yAxis : [
          {
            type : 'value'
          }
        ],
        series
      };
    },
    sortTAble (data = []) {
      data = data.filter(item => {
        return item.count > 0;
      })
      if(data.length == 0) return null;

      let xAxisData = [];
      let unFinishedData = [];
      let series = [];
      
      data.sort((prev, next) => next.count - prev.count);
      data.forEach(item => {
        xAxisData.push(item.tagName);
        unFinishedData.push({
          name: t('report.taskTeamChart.state1'),
          value: item.unCompleteCount || 0,
          _origin: item
        });
      });

      series.push({
        name: t('report.taskTeamChart.state1'),
        type: 'bar',
        barMaxWidth: 30,
        data: unFinishedData,
        barCategoryGap: '30px'
      })

      return {series, xAxisData}
    },
  
    init(start, end){
      this.initChart()
    },
    initChart(){
      chart = echarts.init(document.getElementById('team-chart'));
      window.addEventListener('resize', _.debounce(function(){
        chart.resize();
      }))

      chart.on('click', event => {                  
        let origin = event.data._origin;
        this.model.pageNum = 1;
        this.model.executor = !origin.executorId ? '无' : origin.executorId; 
        this.renderTable();
      })

      chart.on('legendselectchanged', async event => {
        let arr = [];
        for(let [key, value] of Object.entries(event.selected)) {
          arr.push({key, value});
        }
        arr.some(item => {
          if(item.value) {
            this.sort = item.key;
            return true;
          }
        })

        let data = await this.fetchData();

        let opt = chart.getOption(); 
        let sort = this.sortTAble(data);
        opt.series = sort.series;
        opt.xAxis[0].data = sort.xAxisData;
        chart.setOption(opt);
      })

      this.render();
    },
    fetchTableData(){
      let model = {
        pageNum: this.model.pageNum,
        executor: this.model.executor,
        pageSize: 10
      };
      return fetchNoFinishedEventsList(model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);
        
      this.fetchTableData().then(result => {
        this.page = result;
        this.showTable = true;
      })
        .catch(err => console.log(err))
        .finally(() => {
          instance.hide();
        })
    },
    formatState (state) {
      // {"created":"待指派","allocated":"已指派","accepted":"已接受","refused":"已拒绝","processing":"进行中"}   
      let stateName = '';
      switch (state) {
      case 'created':
        stateName = t('common.task.type.created');
        break;
      case 'allocated':
        stateName = t('common.task.type.allocated');
        break;
      case 'accepted':
        stateName = t('common.task.type.accepted');
        break;
      case 'refused':
        stateName = t('common.base.usualStatus.rejected');
        break;
      case 'processing':
        stateName = t('common.task.type.processing');
        break;
      case 'finished':
        stateName = t('common.base.usualStatus.finish');
        break;
      case 'convert2Task':
        stateName = t('common.event.actionStatus.convert2Task');
        break;
      default:
        break;
      }
      return stateName;
    }

  },
  mounted(){
    this.init()
  },
  watch: {
    teamId(){
      this.render();
    }
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>


<style lang="scss">
#team-chart{
  height: 520px;
}
</style>
